package client;

import java.io.IOException;
import java.io.InterruptedIOException;

import javax.xml.bind.JAXBException;

import util.MBMessage;
import util.MBMessageChannelInterface;
import util.MessageHandler;
import util.lib;

public class ClientInstance extends MessageHandler {
	public final static int DEVICE_ARBITER = 0;
	public final static int DEVICE_SERVER = 1;

	/**
	 * Instantiates a client controller to the server.
	 * @param arbiter The channel interface to an arbiter for the user.
	 * @param server The channel interface to the server.
	 * @throws IllegalArgumentException if any parameter is null.
	 */
	public ClientInstance( final MBMessageChannelInterface arbiter, final MBMessageChannelInterface server ) {
		if ( arbiter == null || server == null )
			throw new IllegalArgumentException("A channel was null");
		
		this.arbiter = arbiter;
		this.server = server;
		
		this.registerDevice(DEVICE_ARBITER, arbiter);
		this.registerDevice(DEVICE_SERVER, server);
	}
	
	/**
	 * A channel interface to the arbiter for the user.
	 */
	final protected MBMessageChannelInterface arbiter;
	
	/**
	 * A channel interface to the server.
	 */
	final protected MBMessageChannelInterface server;
	
	@Override
	public void onReaderStart( final Integer dev, final ChannelReader reader ) {
		lib.debug( "Starting reader on device (" + dev +")", lib.FLAG_DEBUG_MSG_HANDLER );
	}

	@Override
	public void onReaderClose( final Integer dev, final ChannelReader reader ) {
		lib.debug( "Closing reader on device (" + dev +")", lib.FLAG_DEBUG_MSG_HANDLER );
	}

	@Override
	public boolean onParsingError( final Integer dev, final JAXBException e ) {
		lib.debug( "Failed to unmarshal on device (" + dev + "): " + e.toString(), lib.FLAG_DEBUG_GENERIC, lib.FLAG_DEBUG_MSG_HANDLER );
		return false;
	}

	@Override
	public boolean onTimeoutError( final Integer dev, final InterruptedIOException e ) {
		lib.debug( "Timed out when reading on device (" + dev +"):" + e.toString(), lib.FLAG_DEBUG_GENERIC, lib.FLAG_DEBUG_MSG_HANDLER );
		return false;
	}

	@Override
	public void OnUnknownIOError( final Integer dev, final IOException e ) {
		lib.debug( "Unknown IO error on device (" + dev + "): " + e.toString(), lib.FLAG_DEBUG_GENERIC, lib.FLAG_DEBUG_MSG_HANDLER );
	}

	@Override
	public void processMessage( final Integer device, final MBMessage msg ) {
		
	}
}
